package service

import (
	"net/http"
	"strconv"

	"github.com/unrolled/render"
)

func apiGetNumHandler(formatter *render.Render) http.HandlerFunc {

	return func(w http.ResponseWriter, req *http.Request) {

		num := strconv.Itoa(len(userList))

		formatter.JSON(w, http.StatusOK, struct {
			Num string `json:"number"`
		}{Num: num})
	}
}

func signUpHandler(formatter *render.Render) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		formatter.HTML(w, http.StatusOK, "signUp", nil)
	}
}

func userProfileHandler(formatter *render.Render) http.HandlerFunc {

	return func(w http.ResponseWriter, req *http.Request) {

		var username, studentID, password string

		req.ParseForm()

		username = req.Form["username"][0]
		studentID = req.Form["studentID"][0]
		password = req.Form["password"][0]

		newUser := user{Username: username, StudentID: studentID, Password: password}
		userList = append(userList, newUser)

		formatter.HTML(w, http.StatusOK, "userProfile", struct {
			Username  string `json:"username"`
			StudentID string `json:"studentid"`
			Password  string `json:"password"`
		}{Username: username, StudentID: studentID, Password: password})
	}
}

func userListHandler(formatter *render.Render) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		formatter.HTML(w, http.StatusOK, "userList", struct {
			UserList []user
		}{UserList: userList})
	}
}

func notImplementedHandler() http.HandlerFunc { return http.HandlerFunc(notImplemented) }

func notImplemented(w http.ResponseWriter, r *http.Request) {
	http.Error(w, "501 Not Implemented", http.StatusNotImplemented)
}
